//
//  ViewController.m
//  StillCamera
//
//  Created by 聚点互动iOS on 2020/12/18.
//

#import "ViewController.h"
#import <GPUImage/GPUImage.h>

@interface ViewController ()
{
    GPUImageStillCamera *_stillCamera;
    GPUImageView *_gpuImageView;
    GPUImageFilter *_filter;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self step1];
    [self step2];
    [self step3];
    [self step4];
    [self step5];
    [self step6];
    
    [self addFuntionBtns];
}


/// 1. 创建并配置 GPUImageStillCamera
- (void)step1{
    GPUImageStillCamera *camera = [[GPUImageStillCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionBack];
    
    // 设置输出图片为竖屏方向
    camera.outputImageOrientation = UIInterfaceOrientationPortrait;
    _stillCamera = camera;
}


/// 2. 创建GPUImageView，用于展示实时的图片效果
- (void)step2{
    GPUImageView *gpuImageView = [[GPUImageView alloc] init];
    gpuImageView.frame = self.view.bounds;
    [self.view addSubview:gpuImageView];
    _gpuImageView = gpuImageView;
}

/// 3. 创建滤镜
- (void)step3{
//    GPUImageFilter *filter  = [[GPUImageFilter alloc] init];
    GPUImageGrayscaleFilter *filter  = [[GPUImageGrayscaleFilter alloc] init];
    
    _filter = filter;
}


/// 4. 为Camera添加滤镜
- (void)step4{
    [_stillCamera addTarget:_filter];
}

/// 5. 为滤镜结果输出给GPUImageView
- (void)step5{
    [_filter addTarget:_gpuImageView];
}


/// 6. 开启会话
- (void)step6{
    [_stillCamera startCameraCapture];
}

/// 拍照
- (void)takePhoto{
    [_stillCamera capturePhotoAsPNGProcessedUpToFilter:_filter withCompletionHandler:^(NSData *processedPNG, NSError *error) {
        
    }];
}

/// 反转摄像头
- (void)rotateCamera{
    //2.切换摄像头
    [_stillCamera rotateCamera];
}

#pragma mark - ****
- (void)addFuntionBtns{
    NSArray<NSString *> *names = @[
        @"反转摄像头",
        @"拍照",
    ];
    
    [names enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
         
        UIButton *btn = [UIButton new];
        [btn setTitle:obj forState:UIControlStateNormal];
        [self.view addSubview:btn];
        btn.tag = idx;
        btn.frame = CGRectMake(0, 100 + idx * 40, 100, 30);
        [btn addTarget:self action:@selector(btnDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    }];
    
}

- (void)btnDidClicked:(UIButton *)sender{
    if (sender.tag == 0) {
        [self rotateCamera];
    }else if(sender.tag == 1){
        [self takePhoto];
    }
}

@end
